package com.zc.manager.device.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.zc.core.ProtocolSupport;
import com.zc.core.ProtocolSupports;
import com.zc.manager.device.domain.IotProtocol;
import com.zc.manager.device.protocol.ProtocolInfo;
import com.zc.manager.device.protocol.TransportInfo;
import com.zc.manager.device.service.IIotProtocolService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 协议管理Controller
 * 
 * @author xiepufeng
 * @date 2022-08-30
 */
@RestController
@RequestMapping("/iot/protocol")
public class IotProtocolController extends BaseController
{
    @Resource
    private IIotProtocolService iotProtocolService;

    @Resource
    private ServerConfig serverConfig;

    @Resource
    private ProtocolSupports protocolSupports;

    /**
     * 查询协议列表
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:list')")
    @GetMapping("/list")
    public TableDataInfo list(IotProtocol iotProtocol)
    {
        startPage();
        List<IotProtocol> list = iotProtocolService.selectIotProtocolList(iotProtocol);
        return getDataTable(list);
    }
    /**
     * 无分页查询
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:list')")
    @GetMapping("/query")
    public AjaxResult query(IotProtocol iotProtocol)
    {
        List<IotProtocol> list = iotProtocolService.selectIotProtocolList(iotProtocol);
        return AjaxResult.success(list);
    }

    /**
     * 导出协议列表
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:export')")
    @Log(title = "导出协议", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotProtocol iotProtocol)
    {
        List<IotProtocol> list = iotProtocolService.selectIotProtocolList(iotProtocol);
        ExcelUtil<IotProtocol> util = new ExcelUtil<>(IotProtocol.class);
        util.exportExcel(response, list, "协议数据");
    }

    /**
     * 获取协议详细信息
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(iotProtocolService.selectIotProtocolById(id));
    }

    /**
     * 新增协议
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:add')")
    @Log(title = "协议管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody IotProtocol iotProtocol)
    {
        return toAjax(iotProtocolService.insertIotProtocol(iotProtocol));
    }

    /**
     * 修改协议
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:edit')")
    @Log(title = "协议管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody IotProtocol iotProtocol)
    {
        return toAjax(iotProtocolService.updateIotProtocol(iotProtocol));
    }

    /**
     * 删除协议
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:remove')")
    @Log(title = "协议管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(iotProtocolService.deleteIotProtocolByIds(ids));
    }

    /**
     * 部署协议
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:edit')")
    @Log(title = "协议部署", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/deploy/{id}")
    public AjaxResult deploy(@PathVariable("id") String id)
    {
        return toAjax(iotProtocolService.deployProtocol(id));
    }
    /**
     * 卸载协议
     */
    @PreAuthorize("@ss.hasPermi('iot:protocol:remove')")
    @Log(title = "协议卸载", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/undeploy/{id}")
    public AjaxResult undeploy(@PathVariable("id") String id)
    {
        return toAjax(iotProtocolService.undeployProtocol(id));
    }

    /**
     * 上传协议文件
     */
    @PostMapping("/file")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getProtocolPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取当前支持的协议
     * @return
     */
    @GetMapping("/supports")
    public AjaxResult getProtocols() {
        return AjaxResult.success(protocolSupports.getProtocols().map(ProtocolInfo::of).buffer().blockFirst());
    }
    /**
     * 获取协议支持的传输协议
     * @return
     */
    @GetMapping("/transports/{id}")
    public AjaxResult transports(@PathVariable("id") String id) {
        return AjaxResult.success(protocolSupports
                .getProtocol(id)
                .flatMapMany(ProtocolSupport::getSupportedTransport)
                .distinct()
                .map(TransportInfo::of)
                .buffer().blockFirst());
    }

}
